package xyz.cerberu.cet.global.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author β世界
 * Created on 8:15
 * @Description
 */
public class RequestUtils {
    /**
     * @author β世界 on 8:16 2020/9/8
     * 获取正确的用户IP地址
     * @param request: 请求对象
     * @return java.lang.String
     **/
    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;

        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代6 理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * @author β世界 on 10:27 2020/10/16
     * 清除指定的cookie
     * @param request: 请求实体
     * @param response: 响应实体
     * @return void
     **/
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response,String cookieName){
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(cookieName.equals(cookie.getName())){
                cookie.setValue(null);
                cookie.setMaxAge(0);
                cookie.setPath("/CeT");
                response.addCookie(cookie);
                break;
            }
        }
    }

    /**
     * 获取请求中的指定cookie内容
     * @author β世界 on 13:23 2021/6/4
     * @param request: 请求体
     * @param cookieName: cookie的名字
     * @return javax.servlet.http.Cookie
     **/
    public static Cookie getCookie(HttpServletRequest request,String cookieName){
        for (javax.servlet.http.Cookie cookie : request.getCookies()) {
            if(cookie.getName().equals(cookieName)){
                return cookie;
            }
        }
        return null;
    }
}
